//https://leetcode.cn/problems/binary-tree-postorder-traversal/
package codeRandomThoughts.Test145二叉树的后序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//统一迭代法
public class Solution3 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> st = new Stack<>();
        if (root != null) st.push(root);

        while (!st.isEmpty()) {
            TreeNode node = st.pop();

            if (node != null) {
                //后序遍历 左右根 反过来是根右左
                st.push(node);
                st.push(null);

                if (node.right != null) st.push(node.right);
                if (node.left != null) st.push(node.left);
            } else {
                TreeNode out = st.pop();
                result.add(out.val);
            }
        }
        return result;
    }
}